extends KinematicBody

export var deadzone = 0.5
export var acceleration = 2.5
export var friction = 0.8
export var gravity = 9.8
var vertical_velocity = 0
var velocity = 0
var camera
var linear_velocity = Vector3()
var state_machine

func _ready():
	camera = $Spatial/Camera
	state_machine = $rotation_helper/AnimationTree["parameters/playback"]
	state_machine.start("idle")

func walk(mouse_pos, delta):      #return player linear velocity
	var direction = mouse_pos - translation
	direction.y = 0
	direction = direction.normalized()
	var angle = acos(Vector3(0,0,-1).dot(direction))
	if(mouse_pos.x > translation.x):
		angle = -angle

	if(Input.is_action_just_pressed("atack")):     #rotate player toward the mouse on atacking
		$rotation_helper.rotation.y = angle 

	if(Input.is_action_pressed("walk") &&
	 sqrt(pow(mouse_pos.x-translation.x,2)+
	 pow(mouse_pos.z-translation.z,2)) > deadzone):
		state_machine.travel("walk")
		velocity += acceleration
		$rotation_helper.rotation.y = angle
	else:
		state_machine.travel("idle") 
	velocity *= friction
	linear_velocity = direction*velocity
		
	if(is_on_floor()):
		vertical_velocity = 0
	else:
		vertical_velocity -= gravity*delta

	linear_velocity.y += vertical_velocity
	return(linear_velocity)

func atack(enemy_position, mouse_pos):
	#your ass with this sword I shall pierce
	var direction = mouse_pos - translation
	direction.y = 0
	direction = direction.normalized()
	var direction_to_enemy = enemy_position-translation
	if(direction_to_enemy.normalized().dot(direction) > 0 && 
	direction_to_enemy.length() < 2 && Input.is_action_just_pressed("atack")):        #change with player hit range
		print("katcha!!!")